<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>登录页面</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      background-color: #f4f4f4;
      display: flex;
      justify-content: center;
      align-items: center;
      height: 100vh;
      margin: 0;
    }
    .form-container {
      background-color: #fff;
      padding: 20px;
      border-radius: 5px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    }
    .form-container h2 {
      margin-top: 0;
    }
    .form-container input,
    .form-container button,
    .form-container select {
      width: 100%;
      padding: 10px;
      margin-bottom: 10px;
      border: 1px solid #ccc;
      border-radius: 3px;
      box-sizing: border-box;
      height: 40px;
    }
    .form-container button {
      background-color: #007BFF;
      color: #fff;
      border: none;
      border-radius: 3px;
      cursor: pointer;
    }
    .form-container button:hover {
      background-color: #0056b3;
    }
    .form-container a {
      display: block;
      text-align: center;
      margin-top: 10px;
      color: #007BFF;
      text-decoration: none;
    }
    .form-container a:hover {
      text-decoration: underline;
    }
    .form-container select {
      appearance: none;
      -webkit-appearance: none;
      -moz-appearance: none;
      background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="12" height="6" viewBox="0 0 12 6"><path d="M1 1l5 5 5-5" stroke="%23333" stroke-width="2" fill="none"/></svg>') no-repeat right 10px center;
      background-size: 12px 6px;
      cursor: pointer;
    }
    .form-container select:focus {
      outline: none;
      border-color: #007BFF;
    }
    .captcha-container {
      display: flex;
      margin-bottom: 10px;
    }
    .captcha-container input {
      flex: 2;
      margin-right: 10px;
    }
    .captcha-container button {
      flex: 1;
      padding: 10px;
    }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<div class="form-container">
  <h2>登录</h2>
  <form id="loginForm">
    <input type="text" id="loginUsername" placeholder="用户名" required>
    <input type="password" id="loginPassword" placeholder="密码" required>
    <button type="submit">登录</button>
  </form>
  <a href="#" id="showRegister">没有账号？点击注册</a>
  <a href="#" id="showChangePassword">忘记密码？修改密码</a>
</div>


<div class="form-container" id="registerForm" style="display: none;">
  <h2>注册</h2>
  <form id="registerFormSubmit">
    <input type="text" id="registerUsername" placeholder="用户名" required>
    <input type="email" id="registerEmail" placeholder="邮箱" required>
    <div class="captcha-container">
      <input type="text" id="registerCaptcha" placeholder="验证码" required>
      <button type="button" id="getCaptcha">获取验证码</button>
    </div>
    <input type="password" id="registerPassword" placeholder="密码" required>
    <input type="password" id="registerConfirmPassword" placeholder="确认密码" required>
    <select id="registerRole" required>
      <option value="普通用户">普通用户</option>
      <option value="商家">商家</option>
    </select>
    <button type="submit">注册</button>
  </form>
  <a href="#" id="showLogin">已有账号？点击登录</a>
</div>


<div class="form-container" id="changePasswordForm" style="display: none;">
  <h2>修改密码</h2>
  <form id="changePasswordFormSubmit">
    <input type="text" id="changePasswordUsername" placeholder="用户名" required>
    <input type="email" id="changePasswordEmail" placeholder="邮箱" required>
    <div class="captcha-container">
      <input type="text" id="changePasswordCaptcha" placeholder="验证码" required>
      <button type="button" id="getChangePasswordCaptcha">获取验证码</button>
    </div>
    <input type="password" id="changePasswordNewPassword" placeholder="新密码" required>
    <input type="password" id="changePasswordConfirmNewPassword" placeholder="确认新密码" required>
    <button type="submit">修改密码</button>
  </form>
  <a href="#" id="showLoginFromChangePassword">返回登录</a>
</div>


<script>
  // 存储验证码
  let captchaCode = "";
  let countdownTimer;

  // 获取注册验证码
  function getCaptcha() {
    const email = document.getElementById('registerEmail').value;
    $.ajax({
      url: '/ValidateCode/ValidateCode.do',
      type: 'POST',
      data: JSON.stringify({ email: email }),
      contentType: 'application/json',
      success: function (data) {
        if (data === true || data === "true") {
          alert("验证码已发送，请查看您的邮箱。");
          startCountdown();
        } else {
          alert("获取验证码失败，请稍后重试！");
        }
      },
      error: function (xhr, status, error) {
        console.error('获取验证码失败:', error);
        // 更详细的错误处理，例如根据状态码显示不同错误信息
        if (xhr.status === 400) {
          alert('输入的邮箱格式错误，请检查！');
        } else if (xhr.status === 500) {
          alert('服务器内部错误，请稍后重试！');
        } else {
          alert('获取验证码失败，请稍后重试！');
        }
      }
    });
  }

  // 获取修改密码验证码
  function getChangePasswordCaptcha() {
    const email = document.getElementById('changePasswordEmail').value;
    $.ajax({
      url: '/ValidateCode/ValidateCode.do',
      type: 'POST',
      data: JSON.stringify({ email: email }),
      contentType: 'application/json',
      success: function (data) {
        if (data === true || data === "true") {
          alert("验证码已发送，请查看您的邮箱。");
          startChangePasswordCountdown();
        } else {
          alert("获取验证码失败，请稍后重试！");
        }
      },
      error: function (xhr, status, error) {
        console.error('获取验证码失败:', error);
        // 更详细的错误处理，例如根据状态码显示不同错误信息
        if (xhr.status === 400) {
          alert('输入的邮箱格式错误，请检查！');
        } else if (xhr.status === 500) {
          alert('服务器内部错误，请稍后重试！');
        } else {
          alert('获取验证码失败，请稍后重试！');
        }
      }
    });
  }

  // 开始注册倒计时
  function startCountdown() {
    let timeLeft = 60;
    document.getElementById('getCaptcha').disabled = true;
    document.getElementById('getCaptcha').style.backgroundColor = '#ccc';
    document.getElementById('getCaptcha').style.cursor = 'not-allowed';
    countdownTimer = setInterval(function() {
      if (timeLeft <= 0) {
        clearInterval(countdownTimer);
        document.getElementById('getCaptcha').disabled = false;
        document.getElementById('getCaptcha').style.backgroundColor = '#007BFF';
        document.getElementById('getCaptcha').style.cursor = 'pointer';
        document.getElementById('getCaptcha').innerText = '获取验证码';
      } else {
        document.getElementById('getCaptcha').innerText = timeLeft +'秒后重试';
        timeLeft--;
      }
    }, 1000);
  }

  // 开始修改密码倒计时
  function startChangePasswordCountdown() {
    let timeLeft = 60;
    document.getElementById('getChangePasswordCaptcha').disabled = true;
    document.getElementById('getChangePasswordCaptcha').style.backgroundColor = '#ccc';
    document.getElementById('getChangePasswordCaptcha').style.cursor = 'not-allowed';
    countdownTimer = setInterval(function() {
      if (timeLeft <= 0) {
        clearInterval(countdownTimer);
        document.getElementById('getChangePasswordCaptcha').disabled = false;
        document.getElementById('getChangePasswordCaptcha').style.backgroundColor = '#007BFF';
        document.getElementById('getChangePasswordCaptcha').style.cursor = 'pointer';
        document.getElementById('getChangePasswordCaptcha').innerText = '获取验证码';
      } else {
        document.getElementById('getChangePasswordCaptcha').innerText = timeLeft +'秒后重试';
        timeLeft--;
      }
    }, 1000);
  }

  // 显示注册表单
  function showForm(showId, hideId) {
    document.getElementById(hideId).style.display = 'none';
    document.getElementById(showId).style.display = 'block';
  }
  document.getElementById('showRegister').addEventListener('click', function() {
    showForm('registerForm', 'loginForm');
  });
  document.getElementById('showLogin').addEventListener('click', function() {
    showForm('loginForm', 'registerForm');
  });
  document.getElementById('showChangePassword').addEventListener('click', function() {
    showForm('changePasswordForm', 'loginForm');
  });
  document.getElementById('showLoginFromChangePassword').addEventListener('click', function() {
    showForm('loginForm', 'changePasswordForm');
  });

  // 注册表单提交处理
  const registerForm = document.getElementById('registerFormSubmit');
  registerForm.addEventListener('submit', function (event) {
    event.preventDefault();
    const user = {
      username: document.getElementById('registerUsername').value,
      email: document.getElementById('registerEmail').value,
      password: document.getElementById('registerPassword').value,
      confirmPassword: document.getElementById('registerConfirmPassword').value,
      role: document.getElementById('registerRole').value,
      captcha: document.getElementById('registerCaptcha').value
    };
    $.ajax({
      url: '/Login/register',
      type: 'POST',
      data: JSON.stringify(user),
      contentType: 'application/json',
      success: function (data) {
        if (data === true || data === "true") {
          alert('注册成功！');
          // 刷新页面或重定向到当前页面
          window.location.reload();
          // 或者使用 window.location.href = window.location.href;
        } else {
          alert(data.message);
        }
      },
      error: function (xhr, status, error) {
        console.error('注册失败:', error);
        alert('注册失败，请稍后重试！');
      }
    });
  });

  // 修改密码表单提交处理
  const changePasswordForm = document.getElementById('changePasswordFormSubmit');
  changePasswordForm.addEventListener('submit', function (event) {
    event.preventDefault();
    const username = document.getElementById('changePasswordUsername').value;
    const email = document.getElementById('changePasswordEmail').value;
    const captcha = document.getElementById('changePasswordCaptcha').value;
    const newPassword = document.getElementById('changePasswordNewPassword').value;
    const confirmNewPassword = document.getElementById('changePasswordConfirmNewPassword').value;
    if (newPassword!== confirmNewPassword) {
      alert('新密码和确认新密码不一致，请重新输入！');
      return;
    }
    const user = {
      username: username,
      email: email,
      captcha: captcha,
      password: newPassword
    };
    $.ajax({
      url: '/Login/ChangePassworld',
      type: 'POST',
      data: JSON.stringify(user),
      contentType: 'application/json',
      success: function (data) {
        if (data.flag) {
          alert('密码修改成功！');
          // 修改成功后重定向到 login.html 页面
          window.location.href = "login.html";
        } else {
          // 判断错误信息是否为邮箱与用户名不匹配
          if (data.message === "邮箱与用户名不匹配") {
            alert("邮箱不正确");
          } else {
            alert(data.message);
          }
        }
      },
      error: function (xhr, status, error) {
        console.error('修改密码失败:', error);
        alert('修改密码失败，请稍后重试！');
        // 增加对不同错误状态码的处理
        if (xhr.status === 400) {
          alert('请求参数错误，请检查！');
        } else if (xhr.status === 500) {
          alert('服务器内部错误，请稍后重试！');
        }
      }
    });
  });
  // 登录表单提交处理
  $(document).ready(function () {
    $("#loginForm").submit(function (event) {
      event.preventDefault();
      var username = $("#loginUsername").val();
      var password = $("#loginPassword").val();
      $.ajax({
        url: "/Login/login",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify({
          username: username,
          password: password
        }),
        success: function (response) {
          if (response.state) {
            var token = response.token;
            // 将 Token 存储到 cookie 中
            document.cookie = "jwtToken=" + token + "; path=/";
            var userType = response.userType;
            // 根据不同的用户类型跳转不同页面
            switch (userType) {
              case "普通用户":
                window.location.href = "/backend/main.html";
                break;
              case "商家":
                window.location.href = "businessMain.html";
                break;
              case "管理员":
                window.location.href = "/backend/administartor.html";
                break;
              default:
                alert("未知用户类型，请联系管理员");
            }
          } else {
            // 根据后端返回的错误信息显示更详细的提示
            if (response.msg === "用户名或密码错误") {
              alert("用户名或密码不正确，请重新输入！");
            } else {
              alert("登录失败: " + response.msg);
            }
          }
        },
        error: function (xhr, status, error) {
          console.error("登录时发生错误: ", error);
          alert("登录时发生错误: " + error);
        }
      });
    });
  });

  // 为获取验证码按钮添加点击事件
  document.getElementById('getCaptcha').addEventListener('click', getCaptcha);
  document.getElementById('getChangePasswordCaptcha').addEventListener('click', getChangePasswordCaptcha);

  // 发起需要授权的请求示例
  function fetchMainPage() {
    const token = localStorage.getItem('jwtToken');
    if (!token) {
      alert('请先登录！');
      return;
    }
    $.ajax({
      url: 'http://localhost/backend/main.html',
      type: 'GET',
      headers: {
        'Authorization': 'Bearer'+ token
      },
      success: function (data) {
        console.log(data);
        // 处理请求成功的数据
        // 可以在这里添加更多的处理逻辑，例如将返回的数据显示在页面上
      },
      error: function (xhr, status, error) {
        console.error('请求失败:', error);
        // 更详细的错误处理，例如根据状态码显示不同错误信息
        if (xhr.status === 401) {
          alert('未授权，请登录！');
          localStorage.removeItem('jwtToken'); // 移除无效的 Token
          showForm('loginForm', '');
        } else if (xhr.status === 403) {
          alert('权限不足！');
        } else {
          alert('请求失败，请稍后重试！');
        }
      }
    });
  }

  // 页面加载时检查 Token
  $(document).ready(function() {
    const token = localStorage.getItem('jwtToken');
    if (token) {
      // 可以在这里添加更复杂的 Token 有效性检查，例如解析 Token 检查过期时间
      fetchMainPage();
    } else {
      showForm('loginForm', '');
    }
  });
</script>
</body>
</html>